package com.ruoyi.web.controller.text;

import com.ruoyi.TextToClasses.domain.ClassText;
import com.ruoyi.TextToClasses.service.IClassTextService;
import com.ruoyi.classs.domain.Classes;
import com.ruoyi.classs.service.IClassesService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.my.domain.Question;
import com.ruoyi.my.service.IQuestionService;
import com.ruoyi.my.service.impl.QuestionServiceImpl;
import com.ruoyi.notices.domain.Notice;
import com.ruoyi.system.domain.QuestionText;
import com.ruoyi.system.domain.UserTextClass;
import com.ruoyi.system.service.IQuestionTextService;
import com.ruoyi.system.service.IUserTextClassService;
import com.ruoyi.texts.domain.Text;
import com.ruoyi.texts.domain.TextToQuestion;
import com.ruoyi.texts.service.ITextService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 试卷管理Controller
 * 
 * @author ruoyi
 * @date 2024-11-27
 */
@RestController
@RequestMapping("/texts/text")
public class TextController extends BaseController
{
    @Autowired
    private IUserTextClassService userTextClassService;
    @Autowired
    private IQuestionTextService questionTextService;
    @Autowired
    private IClassTextService classTextService;
    @Autowired
    private IClassesService classesService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private ITextService textService;

    /**
     * 查询试卷管理列表
     */
//    @PreAuthorize("@ss.hasPermi('texts:text:list')")
    @GetMapping("/list")
    public TableDataInfo list(Text text)
    {
        startPage();
        List<Text> list = textService.selectTextList(text);
        return getDataTable(list);
    }

    /**
     * 导出试卷管理列表
     */
    @PreAuthorize("@ss.hasPermi('texts:text:export')")
    @Log(title = "试卷管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Text text)
    {
        List<Text> list = textService.selectTextList(text);
        ExcelUtil<Text> util = new ExcelUtil<Text>(Text.class);
        util.exportExcel(response, list, "试卷管理数据");
    }

    /**
     * 获取试卷管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('texts:text:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(textService.selectTextById(id));
    }

    /**
     * 新增试卷管理
     */
    @PreAuthorize("@ss.hasPermi('texts:text:add')")
    @Log(title = "试卷管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Text text)
    {
//        Text text = new Text();
//        System.err.println(SecurityUtils.getUsername());
//        System.err.println(map);
        text.setCreateUser(SecurityUtils.getUserId().toString());
        text.setCreateTime(DateUtils.getNowDate());
        text.setUpdateBy(SecurityUtils.getUserId().toString());
        text.setUpdateTime(DateUtils.getNowDate());
        text.setTeacherId(SecurityUtils.getUserId());
        text.setStatus("1");
////        textService.insertText(text);
//        List<Text> texts = textService.selectTextList(null);
//        Long textId = texts.get(texts.size()-1).getId();
//        ClassText classText = new ClassText();
//        classText.setClassId(Long.valueOf(map.get("classId").toString()));
//        classText.setTextId(textId);
//        classTextService.insertClassText(classText);
//        return null;
        return toAjax(textService.insertText(text));
    }

    /**
     * 修改试卷管理
     */
    @PreAuthorize("@ss.hasPermi('texts:text:edit')")
    @Log(title = "试卷管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Text text)
    {
        return toAjax(textService.updateText(text));
    }

    /**
     * 删除试卷管理
     */
    @PreAuthorize("@ss.hasPermi('texts:text:remove')")
    @Log(title = "试卷管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(textService.deleteTextByIds(ids));
    }
//
//    查询试卷下的所有题
    @GetMapping("/questions/{id}")
    public AjaxResult getQuestions(@PathVariable("id") Long id)
    {
        return success(questionService.selectAllByTextId(id));
    }

//    查询试卷及试卷详情
    @GetMapping("/detalislist")
    public AjaxResult getTextDetalisList(){
        return success(textService.selectAllAndDetalis());
    }

//    试卷得分
    @PostMapping("/score")
    public AjaxResult getScore(@RequestBody TextToQuestion[] ids){
        int grade=0;
        for (TextToQuestion id : ids) {
            final val question = questionService.selectQuestionById(id.getQuestionId());
            if (question.getKey11().equals(id.getChoose())){
                grade=grade+2;
            }
        }
        System.err.println(grade);
//        System.err.println(id);
//        QuestionText questionText = new QuestionText();
//        questionText.setTextId(Long.valueOf(id));
//        List<QuestionText> questionTexts = questionTextService.selectScoreByQuestions(Long.valueOf(id));
//        int i = new Random().nextInt(questionTexts.size());
//        System.err.println(i);
//        Notice notice = new Notice();
//        notice.setCreateTime(DateUtils.getNowDate());
//        notice.setCreateUser(SecurityUtils.getUserId().toString());
//        notice.setStatus(1l);
        return success(grade);
    }

    //查询试卷吗总分
    @GetMapping("/getAllscore/{id}")
    public AjaxResult getAllscore(@PathVariable String id){
        List<QuestionText> questionTexts = questionTextService.selectScoreByQuestions(Long.valueOf(id));
        return success(questionTexts.size()*2);
    }

//    查询某个班级的全部试卷
    @GetMapping("/class/list/{id}")
    public AjaxResult selectAllByTeacherId(@PathVariable Long id){
        return success(textService.selectTextAndClassByClassId(id));
    }

//    查询所有班级的所有试卷
    @GetMapping("/classAndText/list")
    public AjaxResult selectTextAndClassList(){
        return success(textService.selectTextAndClassList(SecurityUtils.getUserId()));
    }

//    查询已加班级的所有试卷

//    在试卷里加题
    @GetMapping("/addQuestions")
    public AjaxResult addQuestions(Long textId,Long questionId){
        QuestionText questionText = new QuestionText();
        questionText.setTextId(textId);
        questionText.setQuestionId(questionId);
        return success(questionTextService.insertQuestionText(questionText));
    }

//    查询某个用户的所有试卷
    @GetMapping("/textByUserId")
    public AjaxResult selectTextAndUserAndClassByUserId(){
        return success(textService.selectTextAndUserAndClassByUserId(SecurityUtils.getUserId()));
    }

//    新增试卷
    @PostMapping("/addTextByUserId")
    public AjaxResult addTextByUserId(@RequestBody Map map){
        System.err.println(map);
        Text text = new Text();
        text.setCreateUser(SecurityUtils.getUserId().toString());
        text.setCreateTime(DateUtils.getNowDate());
        text.setUpdateBy(SecurityUtils.getUserId().toString());
        text.setUpdateTime(DateUtils.getNowDate());
        text.setTeacherId(SecurityUtils.getUserId());
        text.setStatus("1");
        text.setClassId(Long.valueOf(map.get("classId").toString()));
        text.setName(map.get("name").toString());
        ClassText classText = new ClassText();
        textService.insertText(text);
        List<Text> texts = textService.selectTextList(null);
        Long textId = texts.get(texts.size()-1).getId();
        classText.setTextId(textId);
        classText.setClassId(Long.valueOf(map.get("classId").toString()));
        classTextService.insertClassText(classText);
        UserTextClass userTextClass = new UserTextClass();
        userTextClass.setTextId(textId);
        userTextClass.setUserId(SecurityUtils.getUserId());
        userTextClass.setClassId(Long.valueOf(map.get("classId").toString()));
        userTextClassService.insertUserTextClass(userTextClass);
        return success("true");
    }

    @PostMapping("/addQuestionToText")
    public AjaxResult addQuestionToText(@RequestBody Map map){
        System.err.println(map);
        Object questionId = map.get("id");
        Object textId = map.get("textId");
        QuestionText questionText = new QuestionText();
        questionText.setQuestionId(Long.valueOf(questionId.toString()));
        questionText.setTextId(Long.valueOf(textId.toString()));
        questionTextService.insertQuestionText(questionText);
        return success("true");
    }

    @DeleteMapping("/class/{id}")
    public AjaxResult delete(@PathVariable Long id)
    {
        return toAjax(textService.deleteTextById(id));
    }

}
